# -*- coding: utf-8 -*-
# @Time    : 2022/6/22 20:21
# @Author  : AUGUS
# @Email   : augus@jilin.com
# @File    : serializers.py
# @Software: PyCharm
from rest_framework import serializers
from .models import *


# 定义返回哪些数据和数据的检验
class StudentSerializer(serializers.ModelSerializer):
    # classes = serializers.StringRelatedField(label='班级')
    class_name = serializers.CharField(source='classes.name', read_only=True)

    class Meta:
        model = Students
        # fields = '__all__'  # 指定映射字段
        # fields = ['id', 'name', 'age', 'sex']
        # read_only_fields = ['id']  # 设置只读字段
        exclude = ['is_delete']
        extra_kwargs = {
            'age': {'min_value': 0, 'max_value': 200}
        }

    def validate_name(self, value):
        if 'mq' not in value.lower():
            raise serializers.ValidationError('用户名需要包含mq')
        return value

    def validate(self, data):
        if 'mq' not in data['name']:
            raise serializers.ValidationError('用户名需要包含mq')
        elif data['age'] < 18:
            raise serializers.ValidationError('年龄需要大于等于18岁')
        return data

    # id = serializers.IntegerField(label='ID', read_only=True)
    # name = serializers.CharField(max_length=30, label='姓名')
    # age = serializers.IntegerField(label='年龄', required=False)
    # sex = serializers.IntegerField(label='性别', required=False)
    # create_time = serializers.DateTimeField(label='创建时间', required=False)
    # update_time = serializers.DateTimeField(label='更新时间', required=False)
    # # is_delete = serializers.BooleanField(label='逻辑删除', required=False)
    #
    # def create(self, validated_data):
    #     return Students.objects.create(**validated_data)  # 拆包，两个*把{'name':'yige'}变成name=yige
    #
    # def update(self, instance, validated_data):
    #     instance.name = validated_data.get('name', instance.name)
    #     instance.age = validated_data.get('age', instance.age)
    #     instance.sex = validated_data.get('sex', instance.sex)
    #     instance.is_delete = validated_data.get('is_delete', instance.is_delete)
    #     instance.save()
    #     return instance


class StudentsSerializerSimple(serializers.ModelSerializer):
    class Meta:
        model = Students
        fields = ['id', 'name', 'age', 'sex']


class ClassesSerializer(serializers.ModelSerializer):
    students_set = StudentsSerializerSimple(many=True, read_only=True)  # 嵌套序列化，对管理器进行操作

    class Meta:
        model = Classes
        # fields = '__all__'
        exclude = ['is_delete']
